package fm.mongo;

import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.exception.BizException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @修改人：CM
 * @修改时间：2017/3/2 21:01
 */
public class MCondition {
    private MRel rel;
    private ArrayList childCondition;

    public static MCondition create() {
        return new MCondition();
    }

    public static MCondition create(MRel rel) {
        return new MCondition(rel);
    }

    public static MCondition create(String key, String val) {
        return MCondition.create(MRel.all).append(key, val);
    }

    public MCondition() {
        this.rel = MRel.all;
        childCondition = new ArrayList();
    }

    public MCondition(MRel rel) {
        this.rel = rel;
        childCondition = new ArrayList();
    }

    public MRel getRel() {
        return rel;
    }

    public MCondition append(MCondition cc) {
        this.childCondition.add(cc);
        return this;
    }

    public MCondition append(String key, Object val) {
        this.childCondition.add(new BasicDBObject(key, val));
        return this;
    }


    public DBObject toDBObject() throws Exception {
        DBObject conditions = new BasicDBObject();
        for (Object cc : this.childCondition) {
            if (cc instanceof BasicDBObject) {
                BasicDBObject childCondition = (BasicDBObject) cc;
                for (String key : childCondition.keySet()) {
                    Object val = childCondition.get(key);
                    if (MConditionParser.matchVal(this.rel, val)) {
                        conditions.put(key, val);
                    }
                }
                conditions.putAll(((BasicDBObject) cc).toMap());
            } else if (cc instanceof MCondition) {
                DBObject val = ((MCondition) cc).toDBObject();
                conditions.putAll(val);
//                conditions.putAll(MConditionParser.parseCondition(childRel,val));
            } else {
                throw new BizException("unknown instanceof condition:" + cc.getClass());
            }
        }
        if (this.rel.equals(MRel.all) == false) {
            return MConditionParser.parseCondition(this.rel,conditions);
        } else {
           return conditions;
        }
    }

    public static void main(String[] args) throws Exception {
        MCondition mc = MCondition.create(MRel.or);
        mc.append("a","b");
        mc.append("b","1");
        System.out.printf(mc.toDBObject().toString());
    }
}
